package com.example.reagent_management.ui.operatedialog.dialogs

import android.util.Log
import android.view.View
import android.widget.RadioButton
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.example.lib_base.base.BaseDBDialogFragment
import com.example.lib_base.base.DataBindingConfig
import com.example.lib_base.widget.InputTextManager
import com.example.reagent_management.BR
import com.example.reagent_management.R
import com.example.reagent_management.databinding.FragmentInsertReagentBinding
import com.example.reagent_management.room.entity.ReagentInformation
import com.example.reagent_management.service.works.HistoryWork
import com.example.reagent_management.service.works.WorksBuild
import com.example.reagent_management.service.works.setHistoryData
import com.example.reagent_management.ui.operatedialog.viewmodle.ReagentInsertViewModel
import com.hjq.toast.ToastUtils
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import javax.inject.Inject

@AndroidEntryPoint
class ReagentInsertFragment : BaseDBDialogFragment() {
    private val mState: ReagentInsertViewModel by viewModels()
    private var makeChange = false
    private lateinit var info: ReagentInformation
    @Inject
    lateinit var works : WorksBuild

    override fun initViewOrObserve() {
        setTransAndHeight(true, 0.5f, true)
        (getBinding() as FragmentInsertReagentBinding).apply {
            setOnDataListener { any ->
                (any as ReagentInformation).let {
                    makeChange = true
                    delete.visibility = View.VISIBLE
                    title.text = "修改试剂"
                    info = it
                    newNum.setText(it.projectName)
                    newName.setText(it.reagentName)
                    when (it.reagentType) {
                        "免疫" -> (type.getChildAt(0) as RadioButton).isChecked = true
                        "生化" -> (type.getChildAt(1) as RadioButton).isChecked = true
                        "电解质" -> (type.getChildAt(2) as RadioButton).isChecked = true
                    }
                    delete.setOnClickListener { _ ->
                        lifecycleScope.launch(Dispatchers.IO) {
                            val result = async {
                                return@async mState.delete(it.reagent_id)
                            }
                            if (result.await() != -1) {
                                ToastUtils.show("删除成功")
                                dismissAllowingStateLoss()
                            }
                        }
                    }
                }
            }
            InputTextManager.with(lifecycleOwner)
                .addView(newNum)
                .addView(newName)
                .setMain(sure)
                .build()
            var typeReagent = getText(R.string.immunity).toString()
            type.setOnCheckedChangeListener { _, checkedId ->
                when (checkedId) {
                    R.id.radioButton -> typeReagent = getText(R.string.immunity).toString()
                    R.id.radioButton2 -> typeReagent = getText(R.string.biochemical).toString()
                    R.id.radioButton3 -> typeReagent = getText(R.string.electrolyte).toString()
                }
            }
            back.setOnClickListener { dismissAllowingStateLoss() }
            sure.setOnClickListener {
                it.isClickable = false
                back.isClickable = false
                lifecycleScope.launch(Dispatchers.IO) {
                    if (!makeChange) {
                        val insertInfo = async {
                            return@async mState.insertInfo(
                                ReagentInformation(
                                    newNum.text.toString(),
                                    newName.text.toString(),
                                    typeReagent
                                )
                            )
                        }
                        //async await具有串行并行作用，对于某些场景有特殊作用
                        //也可以使用withContext
                        val result = insertInfo.await()
                        if (result != -1L) {
                            dismissAllowingStateLoss()
                            ToastUtils.show("新增试剂成功")
                        } else {
                            ToastUtils.show("新增试剂失败，\n请检查试剂是否已存在")
                        }
                    } else {
                        if (info.reagentType.equals(typeReagent) &&
                            info.reagentName.equals(newName.text.toString()) &&
                            info.projectName.equals(newNum.text.toString())
                        ) {
                            ToastUtils.show("请先进行修改")
                        } else {
                            val updateInfo = ReagentInformation(
                                newNum.text.toString(),
                                newName.text.toString(),
                                typeReagent
                            )
                            updateInfo.reagent_id = info.reagent_id
                            val result = mState.update(updateInfo)
                            if (result != 0) {
                                //TODO 更新信息和历史 应该交给后台
                                val data = setHistoryData(
                                    arrayOf(newName.text.toString()),
                                    longArrayOf(
                                        info.reagent_id
                                    ),operate = false,true
                                )
                                works.Builder().setInputData(data, HistoryWork::class.java).build()
                                ToastUtils.show("已修改")
                                dismissAllowingStateLoss()
                            } else {
                                ToastUtils.show("修改失败")
                            }
                        }
                    }
                    it.isClickable = true
                    back.isClickable = true
                }
            }
        }
    }

    override fun getDataBindingConfig(): DataBindingConfig {
        return DataBindingConfig(R.layout.fragment_insert_reagent, BR.VM, mState)
    }
}